import React, { ReactNode, useState, useMemo } from "react";
import { Pagination } from "../pagination";
import { Icon } from "../icon";
import { color } from "../shared/styles";
import { MapData } from "./utils";

export interface SourceDataType {
  key: string;
  [key: string]: any;
}
export interface ColumnType {
  title: ReactNode;
  /** 排序等操作用来代替这列的 */
  dataIndex: string;
  sorter?: {
    compare: (a: SourceDataType, b: SourceDataType) => number;
  };
  render?: (v: any, value: SourceDataType, rowData: ColumnType) => ReactNode;
}
export type TableProps = {
  /** 表内数据部分 */
  data: SourceDataType[];
  /** 表头部分*/
  columns: ColumnType[];
  /** 是否开启排序 */
  sorted?: boolean;
  /** 是否开启页码 */
  pagination?: boolean;
  /** 开启页码时才有效，设置每页显示几个*/
  pageSize?: number;
};

export function Table(props: TableProps) {
  const { data, columns, pageSize, pagination, sorted } = props;
  const [columnData, setColumnData] = useState<ColumnType[]>([]);
  const [sortedData, setSortedData] = useState<SourceDataType[]>([]);
  const [filterState, setFilterState] = useState<number[]>([]); //记录第几列开启筛选
  const [sourceData, setSourceData] = useState<SourceDataType[]>([]);
  const [paginationData, setPaginationData] = useState<SourceDataType[][]>([]);
  const [current, setCurrent] = useState(0); //这个是paginationData的索引
  const originPagination = useMemo(() => {
    return (data: SourceDataType[]) => {
      let tmp: SourceDataType[][] = [];
      let len = data.length;
      let pagenumber = Math.ceil(len / pageSize!); //页数
      for (let i = 0; i < pagenumber; i++) {
        //每页该显示多少内容做好。
        tmp[i] = data.slice(0 + i * pageSize!, pageSize! + i * pageSize!);
      }
      setPaginationData(tmp);
    };
  }, [pageSize]);
  const totalColumn = useMemo(() => {
    //表头总长
    setColumnData(columns); //表头拿来渲染
    setFilterState(new Array(columns.length).fill(0)); //初始化排序数据
    return columns.length;
  }, [columns]);
  const totalLen = useMemo(() => {
    //内容部分总长
    setSourceData(data); //数据
    if (pagination) {
      //分页走paginationData
      originPagination(data);
    }
    return data.length;
  }, [data, originPagination, pagination]);
  const renderData = useMemo(() => {
    //内容部分渲染
    let render;
    if (pagination && paginationData.length !== 0) {
      //如果分页，渲染分页
      render = MapData(paginationData[current], columnData);
    } else {
      //否则直接渲染
      if (sortedData.length === 0) {
        render = MapData(sourceData, columnData);
      } else {
        //如果排序有数据，就按排序渲染
        render = MapData(sortedData, columnData);
      }
    }
    return render;
  }, [columnData, current, pagination, paginationData, sortedData, sourceData]);

  return (
    <div>
      <table>
        <thead>
          <tr>
            {columnData.map((v, i) => {
              return (
                <th key={i}>
                  <span>{v.title}</span>
                  {v.sorter && sorted && v.sorter.compare && (
                    <span
                      onClick={() => {
                        if (filterState[i]) {
                          //如果已经开启了排序
                          //查看是不是1，如果为1，进行逆序排序，否则清空
                          if (filterState[i] === 1) {
                            let res = sourceData
                              .slice()
                              .sort((a, b) => -v.sorter!.compare(a, b)); //数据传给compare
                            let newfilter = new Array(totalColumn).fill(0);
                            newfilter[i] = 2;
                            setSortedData(res);
                            setFilterState(newfilter);
                          } else {
                            setSortedData([]); //清空排序数据
                            if (pagination) {
                              originPagination(data);
                            }
                            filterState[i] = 0;
                            setFilterState([...filterState]);
                          }
                        } else {
                          //没有开启就开启排序
                          let res = sourceData.slice().sort(v.sorter!.compare); //数据传给compare
                          let newfilter = new Array(totalColumn).fill(0);
                          newfilter[i] = 1;
                          setSortedData(res);
                          setFilterState(newfilter);
                        }
                      }}
                    >
                      <Icon
                        icon="arrowup"
                        block
                        color={
                          filterState[i] === 1 ? color.primary : color.dark
                        }
                      ></Icon>
                      <Icon
                        icon="arrowdown"
                        block
                        color={
                          filterState[i] === 2 ? color.primary : color.dark
                        }
                      ></Icon>
                    </span>
                  )}
                </th>
              );
            })}
          </tr>
        </thead>
        <tbody>{renderData}</tbody>
      </table>
      {pagination && (
        <Pagination
          style={{ justifyContent: "flex-end" }}
          total={totalLen}
          pageSize={pageSize}
          callback={(v) => setCurrent(v - 1)}
          defaultCurrent={1}
        ></Pagination>
      )}
    </div>
  );
}

Table.defaultProps = {
  sorted: false,
  pagination: false,
  pageSize: 10,
};
